package club.calong.sanniu.pojo.type;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.tomcat.util.buf.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

// 数据库中该字段存储的类型
@MappedJdbcTypes(JdbcType.VARCHAR)
// 需要转换的对象
@MappedTypes(List.class)
public class StringListConverter extends BaseTypeHandler<List<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {

        if (strings.size() > 0) {
            preparedStatement.setString(i, StringUtils.join(strings, ','));
        } else
            preparedStatement.setString(i, null);
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, String s) throws SQLException {

        if (resultSet.getString(s) == null)
            return null;
        else
            return Arrays.asList(resultSet.getString(s).split(","));
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {

        if (resultSet.getString(i) == null)
            return null;
        else
            return Arrays.asList(resultSet.getString(i).split(","));
    }

    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {

        if (callableStatement.getString(i) == null)
            return null;
        else
            return Arrays.asList(callableStatement.getString(i).split(","));
    }
}
